<template>
  <div class="profile-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>个人中心</span>
        </div>
      </template>

      <el-tabs v-model="activeTab">
        <el-tab-pane label="个人信息" name="info">
          <el-form :model="profileForm" :rules="profileRules" ref="profileFormRef" label-width="120px" style="max-width: 600px">
            <el-form-item label="用户名">
              <el-input v-model="profileForm.username" disabled />
            </el-form-item>
            <el-form-item label="角色">
              <el-tag :type="profileForm.role === 'admin' ? 'danger' : 'info'">
                {{ profileForm.role === 'admin' ? '管理员' : '普通用户' }}
              </el-tag>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="profileForm.email" placeholder="请输入邮箱" />
            </el-form-item>
            <el-form-item label="电话" prop="phone">
              <el-input v-model="profileForm.phone" placeholder="请输入电话" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleUpdateProfile" :loading="updating">
                保存修改
              </el-button>
            </el-form-item>
          </el-form>
          <el-divider class="danger-divider" />
          <div class="danger-zone">
            <div class="danger-text">
              <h4>注销账户</h4>
              <p>注销后将删除个人资料、收藏、预约及借阅记录（已归还），且操作不可恢复。</p>
            </div>
            <el-button type="danger" plain @click="handleDeleteAccount" :loading="deleting">
              永久注销
            </el-button>
          </div>
        </el-tab-pane>

        <el-tab-pane label="修改密码" name="password">
          <el-form :model="passwordForm" :rules="passwordRules" ref="passwordFormRef" label-width="120px" style="max-width: 600px">
            <el-form-item label="当前密码" prop="oldPassword">
              <el-input v-model="passwordForm.oldPassword" type="password" placeholder="请输入当前密码" />
            </el-form-item>
            <el-form-item label="新密码" prop="newPassword">
              <el-input v-model="passwordForm.newPassword" type="password" placeholder="请输入新密码" />
            </el-form-item>
            <el-form-item label="确认新密码" prop="confirmPassword">
              <el-input v-model="passwordForm.confirmPassword" type="password" placeholder="请再次输入新密码" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleChangePassword" :loading="changing">
                修改密码
              </el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { userAPI } from '../services/api'
import { useAuthStore } from '../stores/auth'

const activeTab = ref('info')
const profileFormRef = ref(null)
const passwordFormRef = ref(null)
const updating = ref(false)
const changing = ref(false)
const deleting = ref(false)

const router = useRouter()
const authStore = useAuthStore()

const profileForm = reactive({
  username: '',
  role: '',
  email: '',
  phone: ''
})

const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const validateConfirmPassword = (rule, value, callback) => {
  if (value !== passwordForm.newPassword) {
    callback(new Error('两次输入密码不一致'))
  } else {
    callback()
  }
}

const profileRules = {
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
}

const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少6个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    { validator: validateConfirmPassword, trigger: 'blur' }
  ]
}

const fetchProfile = async () => {
  try {
    const response = await userAPI.getProfile()
    const user = response.user
    profileForm.username = user.username || ''
    profileForm.role = user.role || ''
    profileForm.email = user.email || ''
    profileForm.phone = user.phone || ''
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '获取个人信息失败')
  }
}

const handleUpdateProfile = async () => {
  if (!profileFormRef.value) return
  
  await profileFormRef.value.validate(async (valid) => {
    if (valid) {
      updating.value = true
      try {
        await userAPI.updateProfile({
          email: profileForm.email,
          phone: profileForm.phone
        })
        ElMessage.success('修改成功')
        await fetchProfile()
      } catch (error) {
        ElMessage.error(error.response?.data?.message || '修改失败')
      } finally {
        updating.value = false
      }
    }
  })
}

const handleChangePassword = async () => {
  if (!passwordFormRef.value) return
  
  await passwordFormRef.value.validate(async (valid) => {
    if (valid) {
      changing.value = true
      try {
        await userAPI.changePassword({
          oldPassword: passwordForm.oldPassword,
          newPassword: passwordForm.newPassword
        })
        ElMessage.success('密码修改成功')
        // 重置表单
        passwordForm.oldPassword = ''
        passwordForm.newPassword = ''
        passwordForm.confirmPassword = ''
        if (passwordFormRef.value) {
          passwordFormRef.value.resetFields()
        }
      } catch (error) {
        ElMessage.error(error.response?.data?.message || '密码修改失败')
      } finally {
        changing.value = false
      }
    }
  })
}

const handleDeleteAccount = async () => {
  try {
    await ElMessageBox.confirm(
      '注销后将立即退出并删除所有关联数据（包括收藏、预约、已归还借阅记录等），操作不可恢复。确定继续？',
      '危险操作确认',
      {
        confirmButtonText: '确认注销',
        cancelButtonText: '取消',
        type: 'warning',
        confirmButtonClass: 'el-button--danger'
      }
    )
  } catch (error) {
    return
  }

  deleting.value = true
  try {
    await userAPI.deleteAccount()
    ElMessage.success('账户已注销')
    authStore.clearAuth()
    router.push('/login')
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '注销失败')
  } finally {
    deleting.value = false
  }
}

onMounted(() => {
  fetchProfile()
})
</script>

<style scoped>
.profile-container {
  height: 100%;
}

.card-header {
  font-size: 18px;
  font-weight: 600;
}

.danger-divider {
  margin: 32px 0 20px;
}

.danger-zone {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background-color: #fff5f5;
  border: 1px solid #ffb4b4;
  border-radius: 8px;
  padding: 16px 20px;
  gap: 16px;
  flex-wrap: wrap;
}

.danger-text h4 {
  margin: 0 0 6px;
  color: #c45656;
}

.danger-text p {
  margin: 0;
  color: #a94442;
  font-size: 13px;
}
</style>

